import React, { memo, useEffect, useRef, useState } from 'react';
import {
  ConfigProvider,
  Divider,
  Table,
  Modal,
  Button,
  Form,
  Input,
  Popconfirm,
  Space,
  Dropdown,
  message,
  Drawer,
  Menu,
  Descriptions,
  Col,
  Row
} from 'antd';
import { ProForm } from '@/base-ui';
import DivWrapper from './style';
import zhCN from 'antd/es/locale/zh_CN';
import http from '@/services/request';
import store from '@/pages/home/store';
import {
  PageSearchConfig,
  SearchSelector,
  DataType,
  UseSearch
} from './config';
import { action3, action4 } from '@/pages/home/createAction';
import { Time } from '@/components/getTIme';
//form
const NewForm: (props: any) => JSX.Element = (props: any) => {
  return (
    <Form
      ref={props.newref}
      layout={'vertical'}
      style={{
        minHeight: '100%',
        flex: 1,
        overflow: 'auto',
        width: '100%',
        overflowX: 'hidden'
      }}
    >
      <Row>
        <Col xs={{ span: 5, offset: 2 }} lg={{ span: 8, offset: 2 }}>
          <Form.Item
            label="请输入供货单位"
            name="deliveryUnit"
            rules={[{ required: true, message: '请输入供货单位' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="请输入货物名称"
            name="matName"
            rules={[{ required: true, message: '请输入货物名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="phone"
            label="请输入电话号码"
            rules={[{ required: true, message: '请输入电话号码' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="请输入货物净重(kg)"
            name="netWeight"
            rules={[{ required: true, message: '请输入货物净重(kg)' }]}
          >
            <Input />
          </Form.Item>
        </Col>
        <Col xs={{ span: 5, offset: 2 }} lg={{ span: 8, offset: 2 }}>
          <Form.Item
            name="grossWeight"
            label="请输入货物毛重"
            rules={[{ required: true, message: '请输入货物毛重' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="quantity"
            label="请输入货物数量"
            rules={[{ required: true, message: '请输入货物数量' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="supervisor"
            label="请输入监督人名称"
            rules={[{ required: true, message: '请输入监督人名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="请输入收货人名称"
            name="receiver"
            rules={[{ required: true, message: '请输入收货人名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="receivingUnit"
            label="请输入收货单位"
            rules={[{ required: true, message: '请输入收货单位' }]}
          >
            <Input />
          </Form.Item>
        </Col>
      </Row>
    </Form>
  );
};
//按钮组
const Buttongroup: (props: any) => JSX.Element = (props: any) => {
  return (
    <div style={{ marginBottom: 10, float: 'left' }}>
      <Button
        type="primary"
        onClick={() => props.add()}
        style={{ marginRight: 10 }}
      >
        新增记录
      </Button>
      <Button
        danger
        onClick={() => {
          props.checkit();
        }}
        style={{ marginRight: 10 }}
      >
        批量删除
      </Button>


    </div>
  );
};
const Weigh = memo(() => {
  //更多功能定位id
  const [Drawerid, setDrawerid]: any = useState({});
  //抽屉开关
  const [DrawerVisible, setDrawerVisible] = useState(false);
  //复选框批量删除
const [itemSelected, setItemSelected] = useState<React.Key[]>([]);  //是否新增
  const [edited, setedited]: any = useState({});
  //高级检索
  const [isMoreSearchShow, setisMoreSearchShow] = useState(false);
  const newref: any = useRef();
  const [dataSource, setDataSource]: any = useState([]);
  const [searchMore, setSearchMore] = useState(false);
  useEffect(() => {
    http.get('/server/weightSlaughter/list/1/10').then((res) => {
      setDataSource(res.data.records);
    });
  }, []);
  //复选框的逻辑
  const selectionType = 'checkbox';
  //复选框的内容设定
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      let res: any[] = [];
      selectedRows.map((i) => res.push(i.id));
      setItemSelected(res);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name
    })
  };
  //批量删除
  const checkit = () => {
    http({
      url: `/server/weightSlaughter/deletion/batch`,
      method: 'delete',
      data: JSON.stringify(itemSelected),
      headers: { 'Content-Type': 'application/json' }
    }).then(() => {
      http.get('/server/weightSlaughter/list/1/10').then((res) => {
        setDataSource(res.data.records);
      });
    });
  };
  //导出
  const exported = () => {
    http({
      method: 'get',
      url: '/server/dailySlaughter/export',
      data: JSON.stringify([1, 4]),
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then((res: any) => {
      const blob = new Blob([res.data], {
        // res 为后台返回数据
        type: 'application/vnd.ms-excel;charset=utf-8' // 导出数据生成excel的格式设置
      });
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a');
        elink.download = Date.now() + `.xlsx`;
        elink.style.display = 'none';
        elink.target = '_blank';
        elink.href = window.URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
      }
    });
  };

  //获取当前时间
  const time = () => {
    var d = new Date();
    const date = d.getDate();
    const year = d.getUTCFullYear();
    const hours = d.getHours();
    const month = d.getMonth() + 1;
    const minutes = d.getMinutes();
    const a = [year, month, date].join('-');
    const b = [hours, minutes].join(':');
    return [a, b].join(' ');
  };
  // 控制对话框显示（新增）
  const [addModalVisible, setAddModalVisible] = useState(false);
  // 对话框确认
  const handleAddModalOk = () => {
    setAddModalVisible(false);
    //如果id存在--就是修改
    if (store.getState().name === '编辑') {
      const newedited = newref.current.getFieldsValue();
      http
        .put(`/server/weightSlaughter/update/${edited}`, {
          ...newedited
        })
        .then((res) => {
          http
            .get('/server/weightSlaughter/list/1/10')
            .then((res) => setDataSource(res.data.records));
        });
      return;
    }
    //id不在--就是新增
    const addData = newref.current.getFieldsValue();
    const {
      deliveryUnit,
      carNumber,
      matName,
      phone,
      netWeight,
      grossWeight,
      quantity,
      supervisor,
      receiver,
      receivingUnit
    } = addData;
    let newdata = {
      deliveryUnit,
      carNumber,
      matName,
      phone,
      netWeight,
      grossWeight,
      quantity,
      supervisor,
      receiver,
      date: time(),
      receivingUnit,
      deleted: false
    };
    http.post('/server/weightSlaughter/save', newdata).then((res) => {
      setDataSource([
        ...dataSource,
        {
          deliveryUnit,
          carNumber,
          matName,
          phone,
          netWeight,
          grossWeight,
          quantity,
          supervisor,
          receiver,
          date: time(),
          receivingUnit
        }
      ]);
    });
  };
  //编辑
  const edit = (id: { id: number }) => {
    setAddModalVisible(true);
    //这里必须单单setField..会报错："表单还没挂载调用了setFieldsValue",应该用异步，设一个定时器
    setTimeout(() => {
      newref.current.setFieldsValue({
        ...id
      });
      store.dispatch(action3('编辑'));
      setedited(id.id);
    }, 0);
  };
  // 对话框取消
  const handleAddModalCancel = () => {
    setAddModalVisible(false);
  };
  const add = () => {
    store.dispatch(action4('新增'));
    setTimeout(() => {
      newref.current.setFieldsValue({
        deliveryUnit: '',
        carNumber: '',
        matName: '',
        phone: '',
        netWeight: '',
        grossWeight: '',
        quantity: '',
        supervisor: '',
        receiver: '',
        date: '',
        receivingUnit: ''
      });
    }, 0);
    setAddModalVisible(true);
  };
  const indexTable = {
    pagination: {
      //每页10条项目
      defaultPageSize: 10,
      //自定义每页显示数目
      showSizeChanger: true,
      //自定义每页显示项目的选项
      pageSizeOptions: ['5', '10', '15'],
      // 输入指定页码跳页
      showQuickJumper: true,
      //全部项目数（最好可以用变量表示，与实际项目数关联）
      total: dataSource?.length
    }
  };
  //table的数据名
  const FormColumns: any = [
    {
      title: '供货单位',
      dataIndex: 'deliveryUnit',
      key: 'deliveryUnit',
      width: 150
    },
    {
      title: '货物名称',
      dataIndex: 'matName',
      key: 'matName',
      width: 150,

    },
    {
      title: '电话号码',
      dataIndex: 'phone',
      key: 'phone',
      width: 150,

    },
    {
      title: '净重（kg）',
      dataIndex: 'netWeight',
      key: 'netWeight',
      width: 150
    },
    {
      title: '毛重（kg）',
      dataIndex: 'grossWeight',
      key: 'grossWeight',
      width: 150
    },
    {
      title: '数量（kg）',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 150
    },
    {
      title: '监督人',
      dataIndex: 'supervisor',
      key: 'supervisor',
      width: 150,
    },
    {
      title: '收货人',
      dataIndex: 'receiver',
      key: 'receiver',
      width: 150,
    },

    {
      title: '收货单位',
      dataIndex: 'receivingUnit',
      key: 'receivingUnit',
      width: 150,
    },
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
      width: 150,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
      render: (_: any, record: any) => (
        <Space>
          <a onClick={() => edit(record)}>编辑</a>
          <Popconfirm
            title="确定删除?"
            okText="确认"
            cancelText="取消"
            // cancelButtonProps={{ size: 'middle' }}
            onConfirm={() => {
              http
                .delete(`/server/weightSlaughter/delete/${record.id}`)
                .then((res) => {
                  const newData = dataSource.filter(
                    (item: { id: any }) => item.id !== record.id
                  );
                  setDataSource(newData);
                });
            }}
          >
            <a style={{ color: '#ff4d4f' }}>删除</a>
          </Popconfirm>
          <Dropdown overlay={menu(record)}>
            <a
              onClick={(e) => {
                e.preventDefault();
              }}
            >
              ···
            </a>
          </Dropdown>
        </Space>
      ),
      fixed: 'right'
    }
  ];
  const menu = (item: any) => (
    <Menu
      items={[
        {
          key: 0,
          label: (
            <Button
              type="primary"
              onClick={(e) => {
                showDrawer(item);
              }}
            >
              详情
            </Button>
          )
        },

        {
          key: 2,
          label: (
            <Button
              onClick={function () {
                window.print();
              }}
            >
              打印
            </Button>
          )
        }
      ]}
    />
  );
  // 高级检索 条件查询
  const onFinish = (form: any) => {
    const newform = { ...form, dateStart: Time(form.dateStart._d, true) };
    // 发送请求
    http
      .post('/server/weightSlaughter/conditionGet/1/15', newform)
      .then((res: any) => {
        if (res.statusCode !== 20000) {
          return message.error('查询失败');
        }

        const data = res.data || [];
        setDataSource(data.records);
      });
  };
  //详情--抽屉
  const showDrawer = (data: { id: number }) => {
    setDrawerVisible(true);
    http.get(`/server/weightSlaughter/get/${data.id}`).then((res) => {
      setDrawerid(res.data);
    });
  };
  //关闭抽屉
  const onDraweClose = () => {
    setDrawerVisible(false);
  };
  return (
    <DivWrapper>
      {searchMore && (
        <div>
          <ProForm
            formItems={PageSearchConfig}
            onFinish={(e) => {
              onFinish(e);
            }}
          />
          <Divider style={{ margin: '10px 0 20px' }} />
        </div>
      )}
      <Buttongroup
        checkit={() => checkit()}
        add={() => add()}
        exported={() => exported()}
      ></Buttongroup>
      <UseSearch
        setisMoreSearchShow={(e: boolean) => {
          setisMoreSearchShow(e);
        }}
        isMoreSearchShow={isMoreSearchShow}
        setsearchMore={(e: boolean) => setSearchMore(e)}
      ></UseSearch>
      <SearchSelector
        dataSource={(e: object) => setDataSource(e)}
        style={{ float: 'right' }}
      ></SearchSelector>
      <ConfigProvider locale={zhCN}>
        <Table
          dataSource={dataSource}
          columns={FormColumns}
          scroll={{ x: 1300 }}
          pagination={indexTable.pagination}
          rowKey={(i) => i.id}
          rowSelection={{
            type: selectionType,
            ...rowSelection
          }}
        ></Table>
      </ConfigProvider>
      <Drawer
        title="详情"
        placement="right"
        size="large"
        onClose={onDraweClose}
        visible={DrawerVisible}
      >
        <Descriptions title={'货物名称：'} bordered style={{ width: '450px' }}>
          <Descriptions.Item label="供货单位">
            {Drawerid.deliveryUnit}
          </Descriptions.Item>
          <Descriptions.Item label="电话号码">
            {Drawerid.phone}
          </Descriptions.Item>
          <Descriptions.Item label="货物毛重">
            {Drawerid.grossWeight}
          </Descriptions.Item>
          <Descriptions.Item label="货物净重">
            {Drawerid.netWeight}
          </Descriptions.Item>
          <Descriptions.Item label="监督人">
            {Drawerid.supervisor}
          </Descriptions.Item>
          <Descriptions.Item label="收货人">
            {Drawerid.receiver}
          </Descriptions.Item>
          <Descriptions.Item label="收获单位">
            {Drawerid.receivingUnit}
          </Descriptions.Item>
        </Descriptions>
      </Drawer>
      <Modal
        width={'600px'}
        centered
        bodyStyle={{
          display: 'flex',
          flexDirection: 'column-reverse'
        }}
        title="新增记录"
        visible={addModalVisible}
        onOk={handleAddModalOk}
        onCancel={handleAddModalCancel}
      >
        <NewForm newref={newref}></NewForm>
      </Modal>
    </DivWrapper>
  );
});
export default Weigh;
